//
//  KABCosplayPublishVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/8.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABCosplayPublishVC.h"
#import "KABCosPublishCCell.h"
#import "KABCosPublishCRView.h"
#import "KABCosPubEditVC.h"
#import "KABModel.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "MBProgressHUD+XDPrompt.h"
#import "XDQiniuManager.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import <CoreLocation/CoreLocation.h>
#import "NSString+XDLink.h"
#import "KABCosTopicSeaVC.h"
#import "KABCosAtUserVC.h"

@interface KABCosplayPublishVC ()<UICollectionViewDelegate, UICollectionViewDataSource, CLLocationManagerDelegate, KABCosPublishCCellDelegate, TZImagePickerControllerDelegate, KABCosPublishCRViewDelegate>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (nonatomic, strong) KABCosPublishModel *pubModel;

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (copy,   nonatomic) NSString *locationCity;   // 定位城市

@end

static NSString *const kReuseCellId = @"KABCosPublishCCell";
static NSString *const kReuseCRViewId = @"KABCosPublishCRView";
static NSInteger const kMaxPictureCnt = 9;

@implementation KABCosplayPublishVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = @"发布Cos";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBarBtnTapped:)];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(publishBarBtnTapped:)];
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    UINib *cRViewNib = [UINib nibWithNibName:kReuseCRViewId bundle:nil];
    [self.collectionView registerNib:cRViewNib forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    // 开启定位
    [self getLocation];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return (self.pubModel.cosplay_detail.count < kMaxPictureCnt) ? self.pubModel.cosplay_detail.count + 1 : kMaxPictureCnt;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABCosPublishCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    KABCosPublishItem *item = nil;
    if (indexPath.row < self.pubModel.cosplay_detail.count) {
        item = self.pubModel.cosplay_detail[indexPath.row];
    }
    [cell configViewWithPublishItem:item];
    cell.delegate = self;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        KABCosPublishCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId forIndexPath:indexPath];
        header.pubModel = self.pubModel;
        header.delegate = self;
        return header;
    }
    return nil;
}

#pragma mark - <UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(CGRectGetWidth(self.view.bounds), 110.0);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*13 - 2 * 24) / 3.0;
    return CGSizeMake(width, width);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.pubModel.cosplay_detail.count) {
        KABCosPubEditVC *editVC = [[KABCosPubEditVC alloc] init];
        editVC.pubModel = self.pubModel;
        [self.navigationController pushViewController:editVC animated:YES];
    } else {
        // 添加照片
        NSInteger maxCnt = kMaxPictureCnt - self.pubModel.cosplay_detail.count;
        TZImagePickerController * pickerVC = [[TZImagePickerController alloc] initWithMaxImagesCount:maxCnt delegate:self];
        pickerVC.allowPickingVideo = NO;
        pickerVC.allowTakePicture = NO;
//        pickerVC.allowPickingOriginalPhoto = NO;
        [self presentViewController:pickerVC animated:YES completion:nil];
    }
}

#pragma mark - KABCosPublishCRViewDelegate
- (void)kABCosPublishCRView:(KABCosPublishCRView *)crView topicCharacterInput:(UITextView *)textView {
    KABCosTopicSeaVC *topicVC = [[KABCosTopicSeaVC alloc] init];
    topicVC.viewType = KABCosTopicSeaVCTypePublish;
    topicVC.completeHandle = ^(NSString *topicStr) {
        [self.pubModel addTopicWithTitle:topicStr];
        [self refreshWholeView];
    };
    [self presentViewController:topicVC animated:YES completion:nil];
}

- (void)kABCosPublishCRView:(KABCosPublishCRView *)crView atCharacterInput:(UITextView *)textView {
    KABCosAtUserVC *userVC = [[KABCosAtUserVC alloc] init];
    userVC.completeHandle = ^(NSString *nickname) {
        [self.pubModel addAtUserWithNickname:nickname];
        [self refreshWholeView];
    };
    [self presentViewController:userVC animated:YES completion:nil];
}

#pragma mark - KABCosPublishCCellDelegate
- (void)KABCosPublishCCell:(KABCosPublishCCell *)cell deleteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
    [self.pubModel removePublishItemAtIndex:indexPath.row];
    if (indexPath.row == kMaxPictureCnt - 1) {
        [self.collectionView reloadItemsAtIndexPaths:@[indexPath]];
    } else {
        if (self.pubModel.cosplay_detail.count == kMaxPictureCnt - 1) {
            [self refreshWholeView];
        } else {
            [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
        }
    }
}

#pragma mark - TZImagePickerControllerDelegate
- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    if (isSelectOriginalPhoto) {
        [assets enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            [[TZImageManager manager] getOriginalPhotoWithAsset:obj newCompletion:^(UIImage *photo, NSDictionary *info, BOOL isDegraded) {
//                NSLog(@"获取原图%@， --%@, (%zd)", photos, info, isDegraded);
//                if (!isDegraded) {
//                    [self.pubModel addPublishItemsWithArray:@[photo]];
//                    [self refreshWholeView];
//                }
//            }];
            
            // 上面一个占用内存太大，导致崩溃。所以只能考虑下面这个获取原图的方法。
            [[TZImageManager manager] getOriginalPhotoDataWithAsset:obj completion:^(NSData *data, NSDictionary *info, BOOL isDegraded) {
                NSLog(@"获取原图--%@, (%zd)", info, isDegraded);
                if (!isDegraded) {
                    if (idx < photos.count) {
                        [self.pubModel addPublishItemsWithImgArray:@[photos[idx]] originalDataArray:@[data]];
                        [self refreshWholeView];
                    }
                }
            }];
        }];
    } else {
        [self.pubModel addPublishItemsWithImgArray:photos originalDataArray:nil];
        [self refreshWholeView];
    }
}

//- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
//    NSLog(@"选择照片缩略图 = %@", photos);
//    NSLog(@"选择照片原始的assets = %@", assets);
//    NSLog(@"选取照片之后的infos = %@", infos);
//}

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败：%@", error);
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *location = locations.lastObject;
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (!error) {
            if ([placemarks count] > 0) {
                CLPlacemark *place = [placemarks firstObject];
                
                // 据网上有人说，直辖市没有locality值，需要采用省(自测时发现是有locality的值的)
                self.locationCity = place.locality.length ? place.locality : place.administrativeArea;
                
                NSLog(@"name,%@",place.name);                       // 位置名
                NSLog(@"thoroughfare,%@",place.thoroughfare);       // 街道
                NSLog(@"subThoroughfare,%@",place.subThoroughfare); // 子街道
                NSLog(@"locality,%@",place.locality);               // 市(自测 直辖市也有该值，网上有人说要用省)
                NSLog(@"subLocality,%@",place.subLocality);         // 区
                NSLog(@"administrativeArea, %@", place.administrativeArea); // 省
                NSLog(@"subAdministrativeArea, %@", place.subAdministrativeArea);
                NSLog(@"country,%@",place.country);                 // 国家
                
                //                // 获取城市
                //                NSString *city = placemark.locality;
                //                if (! city) {
                //                    // 6
                //                    city = placemark.administrativeArea;
                //                }
                
            }
        } else {
            NSLog(@"error = %@", error);
        }
    }];
    [manager stopUpdatingLocation];
}

#pragma mark - event response
- (void)cancelBarBtnTapped:(UIBarButtonItem *)item {
    if (self.pubModel.isEmpty) {
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"离开发布页后，编辑内容将被清空" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alertVC addAction:[UIAlertAction actionWithTitle:@"离开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[XDQiniuManager sharedInstance] cancelUpload]; //!< 如果有上传的，直接结束上传
            [self dismissViewControllerAnimated:YES completion:nil];
        }]];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)publishBarBtnTapped:(UIBarButtonItem *)item {
    if (self.pubModel.cosplay_detail.count == 0) {
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"请选择作品图片"];
        return;
    }
    
    // 图片上传成功、发布未成功的情况下，直接去发布即可
    if (self.pubModel.isImgUpload) {
        [self requestPublishCosplay];
        return;
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    [[XDQiniuManager sharedInstance] uploadImgData:self.pubModel.originalImgArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        [self.pubModel updateImgUrlWithArray:urlArray];
        // 发表到服务器
        [self requestPublishCosplay];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}

#pragma mark - private methods
- (void)refreshWholeView {
    [self.collectionView reloadData];
}

- (void)getLocation {
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager requestWhenInUseAuthorization];
        [self.locationManager startUpdatingLocation];
    }
}

- (void)exitViewController {
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.completeHandle) {
            self.completeHandle();
            self.completeHandle = nil;
        }
    }];
}

#pragma mark - network request
- (void)requestPublishCosplay {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 发布帖子
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    NSDictionary *pubDic = [self.pubModel yy_modelToJSONObject];
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_detail" : pubDic[@"cosplay_detail"],
                           @"top_content" : pubDic[@"top_content"],
                           @"address" : self.locationCity,
                           @"topic_list" : [pubDic[@"top_content"] xd_topicStringArray],
                           @"at_list" : [pubDic[@"top_content"] xd_atUserStringArray]};
    NSLog(@"");
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplay] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"发布Cos返回成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self exitViewController];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"发布Cos失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (KABCosPublishModel *)pubModel {
    if (!_pubModel) {
        _pubModel = [[KABCosPublishModel alloc] init];
        _pubModel.topContentMaxLength = KABGlobalCosPubTitleLength;
    }
    return _pubModel;
}

- (CLLocationManager *)locationManager {
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyKilometer]; // 精确度 千米级别
    }
    return _locationManager;
}

- (NSString *)locationCity {
    if (!_locationCity) {
        _locationCity = @"";
    }
    return _locationCity;
}

@end
